import Router from '@koa/router';
const router = new Router();
import projectMemberServices from '../controllers/index.js';
import { verify } from '../utils/jwt/index.js';

router.prefix('/projectMember');

// 获取项目角色列表
router.post('/getRoleList', verify(), async (ctx, next) => {
  const { projectId } = ctx.request.body;
  try {
    const res = await projectMemberServices.getRoleList(projectId);

    if (res) {
      ctx.body = {
        code: 200,
        message: '获取角色列表成功',
        data: res,
      };
    }
  } catch (error) {
    ctx.body = {
      code: 500,
      message: '服务器内部错误',
      data: null,
    };
  }
});

// 获取项目成员列表
router.post('/getProjectMemberList', verify(), async (ctx, next) => {
  try {
    const { filter, projectId, pageNum, pageSize, orderBy } = ctx.request.body;
    const res = await projectMemberServices.getProjecMembertList(
      filter,
      projectId,
      pageNum,
      pageSize,
      orderBy
    );

    const data = {
      list: res.data,
      total: res.pagination.total,
    };

    if (res) {
      ctx.body = {
        code: 200,
        message: '创建成功',
        data,
      };
    }
  } catch (error) {
    ctx.body = {
      code: 500,
      message: '服务器内部错误',
      data: null,
    };
  }
});

// 获取项目成员详情
router.post('/getProjectMemberDetail', verify(), async (ctx, next) => {
  const { id, projectId } = ctx.request.body;
  try {
    const res = await projectMemberServices.getProjectMemberDetail(
      id,
      projectId
    );
    ctx.body = {
      code: 200,
      message: '查询成员详情成功',
      data: res[0],
    };
  } catch (error) {
    ctx.body = {
      code: 500,
      message: '服务器内部错误',
      data: null,
    };
  }
});

// 更新项目成员详情
router.post('/updateProjectMemberDetail', verify(), async (ctx, next) => {
  const { id, project_id, role_id } = ctx.request.body;
  try {
    const res = await projectMemberServices.updateProjectMemberDetail(
      id,
      project_id,
      role_id
    );
    ctx.body = {
      code: 200,
      message: '更新成员信息成功',
      data: res[0],
    };
  } catch (error) {
    ctx.body = {
      code: 500,
      message: '服务器内部错误',
      data: null,
    };
  }
});

// 删除项目成员
router.post('/deleteProjectMember', verify(), async (ctx, next) => {
  const { id, projectId } = ctx.request.body;
  try {
    const res = await projectMemberServices.deleteProjectMember(id, projectId);
    ctx.body = {
      code: 200,
      message: '删除成功',
      data: res[0],
    };
  } catch (error) {
    ctx.body = {
      code: 500,
      message: '服务器内部错误',
      data: null,
    };
  }
});

// 项目角色的增删改查
router.post('/getRole', verify(), async (ctx, next) => {
  const { projectId, roleId } = ctx.request.body;
  try {
    const res = await projectMemberServices.getRole(projectId, roleId);
    if (res) {
      ctx.body = {
        code: 200,
        message: '查询角色详情成功',
        data: res[0],
      };
    }
  } catch (error) {
    ctx.body = {
      code: 500,
      message: '服务器内部错误',
      data: null,
    };
  }
});

router.post('/createRole', verify(), async (ctx, next) => {
  const { projectId, name, description } = ctx.request.body;
  try {
    const res = await projectMemberServices.createRole(
      projectId,
      name,
      description
    );

    if (res) {
      ctx.body = {
        code: 200,
        message: '添加成功',
        data: null,
      };
    }
  } catch (error) {
    ctx.body = {
      code: 500,
      message: error.message || '服务器错误',
      data: null,
    };
  }
});

router.post('/updateRole', verify(), async (ctx, next) => {
  const { projectId, name, description, roleId } = ctx.request.body;
  try {
    const res = await projectMemberServices.updateRole(
      projectId,
      name,
      description,
      roleId
    );

    if (res) {
      ctx.body = {
        code: 200,
        message: '更新成功',
        data: null,
      };
    }
  } catch (error) {
    ctx.body = {
      code: 500,
      message: error.message || '服务器错误',
      data: null,
    };
  }
});

router.post('/deleteRole', verify(), async (ctx, next) => {
  const { projectId, roleId } = ctx.request.body;
  try {
    const res = await projectMemberServices.deleteRole(projectId, roleId);

    if (res) {
      ctx.body = {
        code: 200,
        message: '角色删除成功',
        data: null,
      };
    }
  } catch (error) {
    ctx.body = {
      code: 500,
      message: '服务器内部错误',
      data: null,
    };
  }
});

// 获取项目角色权限树
router.post('/getRolePermissionTree', verify(), async (ctx, next) => {
  const { projectId, projectRoleId } = ctx.request.body;

  try {
    const res = await projectMemberServices.getRolePermissionTree(
      projectId,
      projectRoleId
    );
    if (res) {
      ctx.body = {
        code: 200,
        message: '角色权限树获取成功',
        data: res,
      };
    }
  } catch (error) {
    ctx.body = {
      code: 500,
      message: '服务器内部错误',
      data: null,
    };
  }
});

// 更新项目角色权限树
router.post('/updateRolePermissionTreeApi', verify(), async (ctx, next) => {
  const { projectRoleId, permissionTree } = ctx.request.body;

  try {
    // 1. 提取所有选中的节点ID
    const extractCheckedKeys = (tree) => {
      let keys = [];
      tree.forEach((node) => {
        if (node.checked) {
          keys.push(node.id);
        }
        if (node.children && node.children.length > 0) {
          keys = [...keys, ...extractCheckedKeys(node.children)];
        }
      });
      return keys;
    };

    const checkedKeys = extractCheckedKeys(permissionTree);

    // 2. 调用服务层方法更新权限
    const res = await projectMemberServices.updateRolePermissions(
      projectRoleId,
      checkedKeys
    );

    if (res) {
      ctx.body = {
        code: 200,
        message: '角色权限更新成功',
        data: res,
      };
    }
  } catch (error) {
    ctx.body = {
      code: 500,
      message: '服务器内部错误',
      data: null,
    };
  }
});

// 获取项目权限
router.post('/getProjectPermissionsApi', verify(), async (ctx, next) => {
  const { id, projectId } = ctx.request.body;
  try {
    const res = await projectMemberServices.getProjectPermissionsApi(
      id,
      projectId
    );
    ctx.body = {
      code: 200,
      message: '获取项目权限成功',
      data: res,
    };
  } catch (error) {
    ctx.body = {
      code: 500,
      message: '服务器内部错误',
      data: null,
    };
  }
});

// 获取所有用户列表
router.post('/getUserList', verify(), async (ctx, next) => {
  try {
    const res = await projectMemberServices.getUserList();
    ctx.body = {
      code: 200,
      message: '获取所有用户列表成功',
      data: res,
    };
  } catch (error) {
    ctx.body = {
      code: 500,
      message: '服务器内部错误',
      data: null,
    };
  }
});

// 添加项目成员
router.post('/addProjectMember', verify(), async (ctx, next) => {
  const { userId, projectId } = ctx.request.body;
  try {
    const res = await projectMemberServices.addProjectMember(userId, projectId);
    ctx.body = {
      code: 200,
      message: '添加项目成员成功',
      data: res,
    };
  } catch (error) {
    // 如果是业务逻辑错误（用户已在项目中），返回400状态码
    if (error.message === '该用户已经是项目成员了') {
      ctx.body = {
        code: 400,
        message: error.message,
        data: null,
      };
    } else {
      // 其他错误返回500状态码
      ctx.status = 500;
      ctx.body = {
        code: 500,
        message: '服务器内部错误',
        data: null,
      };
    }
  }
});

export default router;
